﻿using System;
using System.Net;
using System.Net.Http;
using Polly;
using Polly.Extensions.Http;
using Polly.Retry;
using Polly.Wrap;

namespace DjangoRESTFrameworkDAL
{
    public static class PolicyFactory
    {
        public static AsyncRetryPolicy<HttpResponseMessage> CreateTokenRefreshPolicy()
        {
            return HttpPolicyExtensions
                .HandleTransientHttpError()
                .OrResult(response => response.StatusCode == HttpStatusCode.Unauthorized)
                .WaitAndRetryAsync(1,
                    i =>
                    {
                        var _ = Authentication.RefreshAsync().Result;
                        return TimeSpan.FromSeconds(0);
                    }
                );
        }

        public static AsyncRetryPolicy<HttpResponseMessage> CreateTimeoutRetryPolicy()
        {
            return HttpPolicyExtensions
                .HandleTransientHttpError()
                .OrResult(response => response.StatusCode == HttpStatusCode.Unauthorized)
                .WaitAndRetryAsync(
                    new[]
                    {
                        TimeSpan.FromSeconds(1),
                        TimeSpan.FromSeconds(5),
                        TimeSpan.FromSeconds(10)
                    });
        }

        public static AsyncPolicyWrap<HttpResponseMessage> CreateCommonPolicyWrap()
        {
            return Policy.WrapAsync(CreateTokenRefreshPolicy(), CreateTimeoutRetryPolicy());
        }
    }
}